package com.linktrip.devicesmanager.main;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author CaineZhu 并发测试 
 * 
 * @desc 目前测试结果秒并发200+ 10s可以处理2000+的数据 瓶颈在数据库写入和socket响应(估计和机器配置有关)
 */

public class DeviceTestMain {
	public static byte[] temp = { 0x36, 0x00, 0x02, 0x00, 0x01, 0x2a, 0x00, 0x00, 0x24, 0x37, (byte) 0x81, 0x06, 0x56,
			(byte) 0x97, (byte) 0xac, 0x2f, 0x07, 0x01, 0x01, 0x5e, 0x12, 0x00, 0x00, 0x2a, (byte) 0xe6, (byte) 0x9e,
			0x64, 0x61, 0x3e, 0x19, 0x3f, 0x40, 0x6c, 0x21, 0x6d, (byte) 0x88, (byte) 0x96, 0x60, 0x5e, 0x40,
			(byte) 0xe1, 0x07, 0x03, 0x0f, 0x0f, 0x31, 0x1f, 0x00, 0x01, 0x16, 0x30, 0x00, 0x29, 0x00, 0x00, 0x45 };
	public static final String SERVER_IP = "59.110.170.37";
	public static final int SERVER_PORT = 8877;
	public static int count = 0;

	public static void main(String[] args) throws Exception {
		long start = System.currentTimeMillis();
		new DeviceTestMain().virtualDevices(4000);
		long end = System.currentTimeMillis();
		System.out.println("coast time:"+(end - start));
	}

	public synchronized static void addCount() {
		count++;
	}

	public void virtualDevices(int num) {
		for (int i = 0; i < num; i++) {
			try {
				new Thread(new Runnable() {
					public void run() {
						try {
							deviceConnector();
						} catch (UnknownHostException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
							
						
					}
				}).start();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println(count);
	}

	public void deviceConnector() throws UnknownHostException, IOException {
		Socket socket = new Socket(SERVER_IP, SERVER_PORT);
		OutputStream out = socket.getOutputStream();
		DataOutputStream dout = new DataOutputStream(out);
		DataInputStream dRead = new DataInputStream(socket.getInputStream());

		dout.write(temp);
		dout.flush();
		//System.out.println("wrote done!");

		dout.close();
		dRead.close();
		socket.close();
		addCount();
	}

}